<template>
  <div class="commission-details">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="date-range-filter">
        <span class="filter-label">日期范围：</span>
        <div class="date-picker-group">
          <input 
            type="date" 
            v-model="filters.startDate" 
            class="date-picker"
            :max="filters.endDate"
          />
          <span class="date-separator">至</span>
          <input 
            type="date" 
            v-model="filters.endDate" 
            class="date-picker"
            :min="filters.startDate"
          />
        </div>
      </div>
      
      <div class="status-filter">
        <span class="filter-label">结算状态：</span>
        <select v-model="filters.status" class="status-select">
          <option value="">全部状态</option>
          <option value="pending">待结算</option>
          <option value="withdrawable">可提现</option>
          <option value="withdrawn">已提现</option>
        </select>
      </div>
      
      <button class="filter-button" @click="applyFilters">
        应用筛选
      </button>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">
      <table class="commission-table">
        <thead>
          <tr>
            <th>订单信息</th>
            <th>商品信息</th>
            <th>销售金额</th>
            <th>佣金金额</th>
            <th>结算状态</th>
            <th>日期</th>
          </tr>
        </thead>
        <tbody v-if="!loading && commissions.length > 0">
          <tr v-for="commission in paginatedCommissions" :key="commission.id">
            <td class="order-info">
              <div class="order-number">{{ commission.orderNumber }}</div>
            </td>
            <td class="product-info">
              <div class="product-image">
                <img :src="commission.productImage" :alt="commission.productName" />
              </div>
              <div class="product-details">
                <div class="product-name">{{ commission.productName }}</div>
                <div class="product-quantity">x{{ commission.quantity }}</div>
              </div>
            </td>
            <td class="sales-amount">{{ formatNumber(commission.salesAmount) }} USDT</td>
            <td class="commission-amount">{{ formatNumber(commission.amount) }} USDT</td>
            <td class="settlement-status">
              <span 
                class="status-badge" 
                :class="{
                  'pending': commission.status === 'pending',
                  'withdrawable': commission.status === 'withdrawable',
                  'withdrawn': commission.status === 'withdrawn'
                }"
              >
                {{ getStatusText(commission.status) }}
              </span>
            </td>
            <td class="commission-date">{{ formatDate(commission.createdAt) }}</td>
          </tr>
        </tbody>
        <tbody v-else-if="loading">
          <tr>
            <td colspan="6" class="loading-message">
              <div class="loading-spinner"></div>
              <span>加载中...</span>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="6" class="empty-message">
              暂无佣金记录
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 分页区域 -->
    <div class="pagination-container" v-if="totalPages > 1">
      <div class="pagination-info">
        共 {{ commissions.length }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="pagination-controls">
        <button 
          class="pagination-button" 
          :disabled="currentPage === 1"
          @click="currentPage = 1"
        >
          首页
        </button>
        <button 
          class="pagination-button" 
          :disabled="currentPage === 1"
          @click="currentPage--"
        >
          上一页
        </button>
        <div class="pagination-numbers">
          <button 
            v-for="page in displayedPages" 
            :key="page"
            :class="['page-number', { active: currentPage === page }]"
            @click="currentPage = page"
          >
            {{ page }}
          </button>
        </div>
        <button 
          class="pagination-button" 
          :disabled="currentPage === totalPages"
          @click="currentPage++"
        >
          下一页
        </button>
        <button 
          class="pagination-button" 
          :disabled="currentPage === totalPages"
          @click="currentPage = totalPages"
        >
          末页
        </button>
      </div>
    </div>
    
    <!-- 汇总区域 -->
    <div class="summary-section" v-if="!loading && commissions.length > 0">
      <div class="summary-item">
        <span class="summary-label">本期佣金总额:</span>
        <span class="summary-value">{{ formatNumber(totalCommissionAmount) }} USDT</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">结算中佣金:</span>
        <span class="summary-value">{{ formatNumber(pendingCommissionAmount) }} USDT</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">已结算佣金:</span>
        <span class="summary-value">{{ formatNumber(settledCommissionAmount) }} USDT</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">结算率:</span>
        <span class="summary-value">{{ settlementRate }}%</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { generateCommissionDetailsData } from '@/utils/mockData';

// 定义props
interface Props {
  startDate?: string;
  endDate?: string;
  status?: string;
}

const props = withDefaults(defineProps<Props>(), {
  startDate: '',
  endDate: '',
  status: ''
});

// 组件状态
const loading = ref(true);
const commissions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选状态
const filters = ref({
  startDate: props.startDate || getDefaultStartDate(),
  endDate: props.endDate || getDefaultEndDate(),
  status: props.status || ''
});

// 获取默认开始日期（一个月前）
function getDefaultStartDate() {
  const date = new Date();
  date.setMonth(date.getMonth() - 1);
  return date.toISOString().split('T')[0];
}

// 获取默认结束日期（今天）
function getDefaultEndDate() {
  return new Date().toISOString().split('T')[0];
}

// 加载数据
async function loadData() {
  loading.value = true;
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800));
    
    // 获取模拟数据
    commissions.value = generateCommissionDetailsData({
      startDate: filters.value.startDate,
      endDate: filters.value.endDate,
      status: filters.value.status
    });
    
    // 重置到第一页
    currentPage.value = 1;
  } catch (error) {
    console.error('获取佣金明细失败:', error);
  } finally {
    loading.value = false;
  }
}

// 应用筛选
function applyFilters() {
  loadData();
}

// 状态文本映射
function getStatusText(status: string) {
  const statusMap = {
    'pending': '待结算',
    'withdrawable': '可提现',
    'withdrawn': '已提现'
  };
  return statusMap[status] || status;
}

// 格式化数字
function formatNumber(value: number): string {
  return value.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

// 格式化日期
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 计算属性：总页数
const totalPages = computed(() => {
  return Math.ceil(commissions.value.length / pageSize.value);
});

// 计算属性：当前页的数据
const paginatedCommissions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return commissions.value.slice(start, end);
});

// 计算属性：显示的页码范围
const displayedPages = computed(() => {
  const range = [];
  const delta = 2; // 当前页前后显示的页数
  
  for (
    let i = Math.max(1, currentPage.value - delta);
    i <= Math.min(totalPages.value, currentPage.value + delta);
    i++
  ) {
    range.push(i);
  }
  
  return range;
});

// 计算属性：总佣金金额
const totalCommissionAmount = computed(() => {
  return commissions.value.reduce((sum, commission) => sum + commission.amount, 0);
});

// 计算属性：待结算佣金金额
const pendingCommissionAmount = computed(() => {
  return commissions.value
    .filter(commission => commission.status === 'pending')
    .reduce((sum, commission) => sum + commission.amount, 0);
});

// 计算属性：已结算佣金金额
const settledCommissionAmount = computed(() => {
  return commissions.value
    .filter(commission => commission.status === 'withdrawn')
    .reduce((sum, commission) => sum + commission.amount, 0);
});

// 计算属性：结算率
const settlementRate = computed(() => {
  if (totalCommissionAmount.value === 0) return '0.0';
  return ((settledCommissionAmount.value / totalCommissionAmount.value) * 100).toFixed(1);
});

// 监听页面变化
watch(currentPage, () => {
  // 如果需要，可以在这里添加分页变化后的逻辑
});

// 组件挂载
onMounted(() => {
  loadData();
});
</script>

<style scoped lang="scss">
.commission-details {
  padding: 20px 0;
  
  // 筛选区域
  .filter-section {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 8px;
    
    .filter-label {
      color: #666;
      font-size: 14px;
      margin-right: 8px;
    }
    
    .date-range-filter {
      display: flex;
      align-items: center;
      
      .date-picker-group {
        display: flex;
        align-items: center;
        
        .date-picker {
          padding: 6px 10px;
          border: 1px solid #ddd;
          border-radius: 4px;
          font-size: 14px;
          
          &:focus {
            outline: none;
            border-color: #2196F3;
          }
        }
        
        .date-separator {
          margin: 0 8px;
        }
      }
    }
    
    .status-filter {
      display: flex;
      align-items: center;
      
      .status-select {
        padding: 6px 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        min-width: 120px;
        
        &:focus {
          outline: none;
          border-color: #2196F3;
        }
      }
    }
    
    .filter-button {
      padding: 6px 12px;
      background-color: #2196F3;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:hover {
        background-color: #1976D2;
      }
    }
  }
  
  // 表格区域
  .table-container {
    overflow-x: auto;
    margin-bottom: 20px;
    
    .commission-table {
      width: 100%;
      border-collapse: collapse;
      
      th, td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #eee;
      }
      
      th {
        background-color: #f5f5f5;
        font-weight: 600;
        color: #333;
      }
      
      tbody tr:hover {
        background-color: #f9f9f9;
      }
      
      .order-info {
        .order-number {
          font-weight: 500;
          color: #333;
        }
      }
      
      .product-info {
        display: flex;
        align-items: center;
        
        .product-image {
          width: 40px;
          height: 40px;
          margin-right: 12px;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
          }
        }
        
        .product-details {
          .product-name {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .product-quantity {
            font-size: 13px;
            color: #666;
          }
        }
      }
      
      .sales-amount, .commission-amount {
        font-weight: 500;
      }
      
      .commission-amount {
        color: #4CAF50;
      }
      
      .settlement-status {
        .status-badge {
          display: inline-block;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          font-weight: 500;
          
          &.pending {
            background-color: #FFF8E1;
            color: #FFA000;
          }
          
          &.withdrawable {
            background-color: #E8F5E9;
            color: #4CAF50;
          }
          
          &.withdrawn {
            background-color: #E3F2FD;
            color: #1976D2;
          }
        }
      }
      
      .commission-date {
        color: #666;
        font-size: 13px;
      }
      
      .loading-message, .empty-message {
        text-align: center;
        padding: 40px 0;
        color: #666;
      }
      
      .loading-message {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 12px;
        
        .loading-spinner {
          width: 20px;
          height: 20px;
          border: 2px solid #eee;
          border-top-color: #2196F3;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
      }
    }
  }
  
  // 分页区域
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    
    .pagination-info {
      color: #666;
      font-size: 14px;
    }
    
    .pagination-controls {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .pagination-button {
        padding: 6px 10px;
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover:not(:disabled) {
          background-color: #e9e9e9;
        }
        
        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
      
      .pagination-numbers {
        display: flex;
        gap: 4px;
        
        .page-number {
          width: 32px;
          height: 32px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 4px;
          background-color: #f5f5f5;
          border: 1px solid #ddd;
          cursor: pointer;
          
          &:hover:not(.active) {
            background-color: #e9e9e9;
          }
          
          &.active {
            background-color: #2196F3;
            color: white;
            border-color: #2196F3;
          }
        }
      }
    }
  }
  
  // 汇总区域
  .summary-section {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 24px;
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 8px;
    
    .summary-item {
      display: flex;
      flex-direction: column;
      
      .summary-label {
        font-size: 13px;
        color: #666;
        margin-bottom: 4px;
      }
      
      .summary-value {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
    }
  }
}

// 动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式
@media (max-width: 768px) {
  .commission-details {
    .filter-section {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .date-range-filter, .status-filter {
        width: 100%;
        
        .date-picker-group {
          width: 100%;
          
          .date-picker {
            flex: 1;
          }
        }
      }
    }
    
    .pagination-container {
      flex-direction: column;
      gap: 12px;
      
      .pagination-info {
        text-align: center;
        width: 100%;
      }
    }
    
    .summary-section {
      flex-direction: column;
      gap: 12px;
    }
  }
}
</style> 